/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package github.ishaan.buttonprogressbar.slice;

import com.jaredrummler.materialspinner.MaterialSpinner;
import github.ishaan.buttonprogressbar.ButtonProgressBar;
import github.ishaan.buttonprogressbar.ResourceTable;
import github.ishaan.buttonprogressbar.utils.Toast;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.TextAlignment;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;


public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener,
        MaterialSpinner.OnItemSelectedListener {
    private static final int EVENT_MESSAGE_DELAY_1 = 0x1000001;
    private static final int EVENT_MESSAGE_DELAY_2 = 0x1000002;
    private static final int EVENT_MESSAGE_DELAY_3 = 0x1000003;
    private static final int DELAY_TIME_1 = 20;
    private static final int DELAY_TIME_2 = 20000;
    private static final int DELAY_TIME_3 = 20;
    private static final int MAX_LINE = 2;
    private ButtonProgressBar mLoader;
    private int progress = 0;
    private TestEventHandler handler;
    private EventRunner eventRunner;
    private MaterialSpinner spinner;
    private static final String[] SPINNER_ITEMS = {
            "Determinate",
            "Indeterminate"
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initHandler();
        initView();
    }

    private void initHandler() {
        eventRunner = EventRunner.create("TestRunner");
        handler = new TestEventHandler(eventRunner);
    }

    private void initView() {
        mLoader = (ButtonProgressBar) findComponentById(ResourceTable.Id_cl_main);
        mLoader.setClickedListener(this);
        spinner = (MaterialSpinner) findComponentById(ResourceTable.Id_spinner);
        spinner.setItems(SPINNER_ITEMS);
        spinner.setOnItemSelectedListener((MaterialSpinner.OnItemSelectedListener<String>) (view, position, id, item) -> {
            DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(MainAbilitySlice.this)
                    .parse(ResourceTable.Layout_layout_toast, null, false);
            Text text = (Text) toastLayout.findComponentById(ResourceTable.Id_msg_toast);
            text.setText("Clicked " + item);
            text.setTextAlignment(TextAlignment.LEFT);
            text.setMultipleLine(true);
            text.setMaxTextLines(MAX_LINE);
            text.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
            mLoader.reset();
            switch (position) {
                case 0:
                    mLoader.setLoaderType(ButtonProgressBar.Type.DETERMINATE);
                    break;
                case 1:
                    mLoader.setLoaderType(ButtonProgressBar.Type.INDETERMINATE);
                    break;
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        progress = 0;
        mLoader.reset();
        if (mLoader.getLoaderType() == ButtonProgressBar.Type.DETERMINATE) {
            callHandler();
        } else {
            mLoader.startLoader();
            callHandler2();
            long param = 0L;
            Object object = null;
            InnerEvent delayInnerEvent = InnerEvent.get(EVENT_MESSAGE_DELAY_2, param, object);
            handler.sendEvent(delayInnerEvent, DELAY_TIME_2, EventHandler.Priority.IMMEDIATE);
        }
    }

    private void callHandler() {
        long param = 0L;
        Object object = null;
        InnerEvent delayInnerEvent = InnerEvent.get(EVENT_MESSAGE_DELAY_1, param, object);
        handler.sendEvent(delayInnerEvent, DELAY_TIME_1, EventHandler.Priority.IMMEDIATE);
    }

    private void callHandler2() {
        long param = 0L;
        Object object = null;
        InnerEvent delayInnerEvent = InnerEvent.get(EVENT_MESSAGE_DELAY_3, param, object);
        handler.sendEvent(delayInnerEvent, DELAY_TIME_3, EventHandler.Priority.IMMEDIATE);
    }

    @Override
    public void onItemSelected(MaterialSpinner materialSpinner, int i, long l, Object o) {
        DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(MainAbilitySlice.this)
                .parse(ResourceTable.Layout_layout_toast, null, false);
        Text text = (Text) toastLayout.findComponentById(ResourceTable.Id_msg_toast);
        text.setText("Clicked " + o);
        text.setTextAlignment(TextAlignment.LEFT);
        text.setMultipleLine(true);
        text.setMaxTextLines(2);
        text.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
    }

    private class TestEventHandler extends EventHandler {
        private TestEventHandler(EventRunner runner) {
            super(runner);
        }

        @Override
        public void processEvent(InnerEvent event) {
            switch (event.eventId) {
                case EVENT_MESSAGE_DELAY_1:
                    if (progress <= 100) {
                        updateUI(EVENT_MESSAGE_DELAY_1);
                        progress++;
                        callHandler();
                    } else {
                        getUITaskDispatcher().asyncDispatch(() -> Toast.show(getContext(), "Complete"));
                    }
                    break;
                case EVENT_MESSAGE_DELAY_2:
                    updateUI(EVENT_MESSAGE_DELAY_2);
                    break;
                case EVENT_MESSAGE_DELAY_3:
                    updateUI(EVENT_MESSAGE_DELAY_3);
                    callHandler2();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 更新ui
     *
     * @param type type
     */
    public void updateUI(int type) {
        switch (type) {
            case EVENT_MESSAGE_DELAY_1:
                getUITaskDispatcher().asyncDispatch(() -> mLoader.setProgress(progress));
                break;
            case EVENT_MESSAGE_DELAY_2:
                getUITaskDispatcher().asyncDispatch(
                        () -> {
                            handler.removeAllEvent();
                            mLoader.stopLoader();
                            Toast.show(getContext(), "Complete");
                        });
                break;
            case EVENT_MESSAGE_DELAY_3:
                getUITaskDispatcher().asyncDispatch(() -> mLoader.invalidate());
                break;
        }
    }

}
